package com.book.pay.strategy.factory;

import com.book.pay.strategy.PayStrateInterface;
import com.book.pay.strategy.context.PayContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 具体工厂类
 * @date 2024/2/19 21:55
 */
@Component
public class PayContextFacatory extends AbstractPayContextFacatory<PayContext> {

    private static final Map<String, PayContext> cache = new HashMap<>(2);

    @Override
    public PayContext getContext(Integer payType) {
        StrategyEnum object = payType == 1 ? StrategyEnum.alipay : payType == 2 ? StrategyEnum.weipay : null;
        if (object == null) {
            throw new RuntimeException("nothing !!");
        }
        if(cache.get(object.name()) == null){
            String value = object.getValue();
            try {
                PayStrateInterface payStrateInterface = (PayStrateInterface) Class.forName(value).newInstance();
                cache.put(object.name(),new PayContext(payStrateInterface));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

        return cache.get(object.name());
    }
}
